import { defineConfig, loadEnv, ConfigEnv } from 'vite'
import { createVitePlugins } from './build/index'
import { wrapperEnv } from './build/utils'
import { OUTPUT_DIR } from './build/constant'
import { format } from 'date-fns'

import path from 'path'
import pkg from './package.json'

function resolve(dir: string) {
  return path.join(__dirname, dir)
}
const { dependencies, devDependencies, name, version } = pkg
const __APP_INFO__ = {
  pkg: { dependencies, devDependencies, name, version },
  lastBuildTime: format(new Date(), 'yyyy-MM-dd HH:mm:ss')
}

export default defineConfig((mode: ConfigEnv) => {
  const root = process.cwd()
  const env = loadEnv(mode.mode, root)
  const viteEnv = wrapperEnv(env)
  const {
    VITE_PUBLIC_PATH,
    VITE_DROP_CONSOLE,
    VITE_PORT,
    VITE_VERSION,
    VITE_NAME
  } = viteEnv
  return {
    base: VITE_PUBLIC_PATH,
    plugins: createVitePlugins(viteEnv),
    resolve: {
      alias: [
        {
          find: 'vue-i18n',
          replacement: resolve('node_modules/vue-i18n/dist/vue-i18n.cjs.js')
        },
        {
          find: /\/#\//,
          replacement: resolve('types')
        },
        {
          find: '@',
          replacement: resolve('src')
        },
        {
          find: 'comps',
          replacement: resolve('src/components')
        }
      ],
      dedupe: ['vue']
    },
    define: {
      __APP_INFO__: JSON.stringify(__APP_INFO__),
      'process.env': env,
      __NEXT_VERSION__: JSON.stringify(VITE_VERSION),
      __NEXT_NAME__: JSON.stringify(VITE_NAME)
    },
    server: {
      host: true,
      port: VITE_PORT
    },
    build: {
      minify: 'terser',
      target: 'es2015',
      outDir: OUTPUT_DIR,
      chunkSizeWarningLimit: 2000,
      brotliSize: false,
      terserOptions: {
        compress: {
          keep_infinity: true,
          drop_console: VITE_DROP_CONSOLE,
          drop_debugger: VITE_DROP_CONSOLE
        },
        keep_classnames: true
      },
      rollupOptions: {
        output: {
          chunkFileNames: 'assets/js/[name]-[hash].js',
          entryFileNames: 'assets/js/[name]-[hash].js',
          assetFileNames: 'assets/[ext]/[name]-[hash].[ext]',
          manualChunks(id) {
            if (id.includes('node_modules')) {
              return (
                id
                  .toString()
                  .match(/\/node_modules\/(?!.pnpm)(?<moduleName>[^\/]*)\//)
                  ?.groups!.moduleName ?? 'vender'
              )
            }
          }
        }
      }
    }
  }
})
